%%%-------------------------------------------------------------------
%%% @author Administrator
%%% @copyright (C) 2019, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 26. 12月 2019 13:56
%%%-------------------------------------------------------------------
-module(ws_message).
-author("Administrator").

-include("include/player.hrl").
-include("include/protocol.hrl").
-include("include/logger.hrl").
-include("include/myshare.hrl").
-include("include/game.hrl").
%% API
-export([message_response/3]).

message_response(FormId, _Msg, #player_state{ws_connPid = Ws_Pid})
  when FormId /= Ws_Pid ->
  ok;
%%统一处理收到的消息
message_response(FormId, Msg, PlayerState = #player_state{ws_connPid = Ws_Pid, account = Account2, is_room = Is_room})
  when FormId =:= Ws_Pid ->
  Map = jsx:decode(Msg, [return_maps, {labels, atom}]),
  case maps:get(code, Map) of
    %登录成功
    ?CODE_CONN_SUCCESS ->
      ?INFO("websocket conn success!"),
      database:update_login_state([PlayerState#player_state.task_id, Account2]),
      self() ! {send_ws, ?NIUNIU_MY_INTEGRAL},%获取积分数据
      self() ! {send_ws, ?CODE_USER_INFO}, %获取用户信息
      self() ! {send_ws, ?CODE_ROOM_INFO}; %获取大厅房间数据

    %接收用户信息消息
    ?CODE_USER_INFO ->
      ?DEBUG("CODE_USER_INFO account:~p", [Account2]),
      res_user_info(Map);

    %接收房间数据
    ?CODE_ROOM_INFO ->
      ?DEBUG("code_room_info:~p", [Map]),
      case res_room_info(maps:get(data, Map, [])) of
        [] -> ok;
        Rooms ->
          Rooms2 = #room_info{account = Account2, room_list = Rooms},
          ets:insert(?ETS_ROOM_INFO, Rooms2),
          timer:sleep(1000),
          Room_data =
            case Is_room of
              false -> player_assist:get_first_room(Account2);
              _ -> []
            end,
          case Room_data /= [] andalso PlayerState#player_state.game_pid =:= undefined of
            true ->
              self() ! {start_game, Room_data#room_data.game_type, Room_data#room_data.room_id, Room_data#room_data.type};
            _ -> ok
          end
      end;

    %%获取我的积分
    ?NIUNIU_MY_INTEGRAL ->
      UserCredit = maps:get(userCredit, maps:get(data, Map)),
      {Credit, ClubGroupId} =
        case UserCredit of
          [] -> {0, 0};
          [UserCredit2 | _] ->
            Credit2 = maps:get(credit, UserCredit2),
            ClubGroupId2 = maps:get(clupGroupId, UserCredit2),
            {Credit2, ClubGroupId2}
        end,
      ?DEBUG("player score info score:~p,group_id:~p", [Credit, ClubGroupId]),
      player_assist:update_player_info(Account2, [{#player_info.score, Credit}, {#player_info.group_id, ClubGroupId}]);

    100013 ->
      ?INFO("Be offline ~p", [Map]);

    _ ->
      ?DEBUG("ws_message other msg~p", [Map]),
      ok
  end.

%%玩家信息
res_user_info(Map2) ->
  PlayerInfo = player_assist:get_at_player_info(),
  %更新玩家信息
  Map = maps:get(data, Map2),
  Id = binary_to_list(maps:get(id, Map)),
  NickName = maps:get(nickName, Map),
  FullHeadImg = maps:get(fullHeadImg, Map),
  ?DEBUG("playerinfo map :~p", [Map]),
  %更新ets
  FiledList = [{#player_info.id, Id}, {#player_info.nickName, NickName}, {#player_info.is_new_player, ?NOT_NEW_PLAYER}],
  player_assist:update_player_info(PlayerInfo#player_info.account, FiledList),
  %更新db
  Params = [NickName, Id, FullHeadImg, PlayerInfo#player_info.account],
  ?DEBUG("plyaer info params:~p,playerinfo:~p", [Params, PlayerInfo]),
  case PlayerInfo#player_info.is_new_player == 1 of
    true ->
      database:update_player_info(Params);
    _ -> ok
  end.

res_room_info(List) ->
  Account = player_assist:get_player_account(),
  PlayerState = player_assist:get_player_state(),
  TaskInfo = game_assist:get_task_info(PlayerState#player_state.task_id),
  ?DEBUG("res_room_info TASKinfo : ~p", [TaskInfo]),
  case TaskInfo of
    _ ->
      case List of
        [_ | _] ->
          Fun = fun(L2, Acc) ->
            RoomId = maps:get(roomId, L2),
            GameId = maps:get(gameType, L2),
            %只进入以下游戏的房间
            ?INFO("gameid list member:~p;~p",[GameId,TaskInfo]),
            case lists:member(GameId, TaskInfo#game_task.gameId_list) of
              true ->
                Room = #room_data{
                  id = binary_to_list(maps:get(id, L2)),
                  account = Account,
                  room_id = RoomId,
                  create_date = binary_to_list(maps:get(createDate, L2)),
                  invalid_date = binary_to_list(maps:get(invalidDate, L2)),
                  game_type = GameId,
                  runtime = maps:get(runTime, L2),
                  player_count = maps:get(playerCount, L2),
                  money_type = maps:get(moneyType, L2),
                  type = maps:get(type, L2),
                  allow_integral = maps:get(minScore, L2),
                  max_people = maps:get(max, L2),
                  group_id = maps:get(groupId, L2, 0)
                },
                game_util:init_room_index(GameId, RoomId),
                lists:append(Acc, [Room]);
              _ -> Acc
            end
                end,
          List2 = lists:foldl(Fun, [], List),

          ?DEBUG("room data  ~n~p", [List2]),
          lists:keysort(#room_data.create_date, List2);
        _ -> []
      end
  end.









